from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from .models import User, Address
from goods.models import SKU
import re
from django_redis import get_redis_connection
from celery_tasks.email.tasks import send_email_verify
from .constants import USER_BROWSING_HISTORY_COUNTS_LIMIT


class UserCreateSerializer(serializers.Serializer):
    # 用户名 密码 确认密码 手机号 短信验证码 是否同意
    id = serializers.IntegerField(read_only=True)
    username = serializers.CharField(min_length=5, max_length=20,
                                     error_messages={'min_length': '用户名不得少于5位', 'max_length': '用户名不得超过20位'})
    password = serializers.CharField(min_length=8, max_length=20, write_only=True,
                                     error_messages={'min_length': '密码不得少于8位', 'max_length': '密码不得超过20位'})
    password2 = serializers.CharField(min_length=8, max_length=20, write_only=True)
    mobile = serializers.CharField()
    sms_code = serializers.CharField(write_only=True)
    allow = serializers.CharField(write_only=True)
    token = serializers.CharField(read_only=True, label='登录状态token')

    def validate_username(self, value):
        # 验证用户名是否已存在
        if not re.search(u'^[\u4e00-\u9fa5a-zA-Z]+', value):
            raise serializers.ValidationError('请至少以一个字母或汉字开头命名!')
        count = User.objects.filter(username=value).count()
        if count > 0:
            raise serializers.ValidationError('用户名已存在')
        return value

    def validate_mobile(self, value):
        # 验证手机号是否已注册
        count = User.objects.filter(mobile=value).count()
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式不正确!')
        if count > 0:
            raise serializers.ValidationError('用户名已存在!')
        return value

    def validate_sms_code(self, value):
        # 验证短信验证码是否合法
        if not re.match(r'^\d{6}', value):
            raise serializers.ValidationError('短信验证码格式不正确!')
        return value

    def validate_is_allow(self, value):
        if not value:
            raise serializers.ValidationError('请同意协议!')
        return value

    def validate(self, attrs):
        # 验证两次密码是否一致
        password = attrs.get('password')
        password2 = attrs.get('password2')
        if password != password2:
            raise serializers.ValidationError('两次密码输入不一致')
        # 短信验证码是否正确
        redis_cli = get_redis_connection('verify_code')
        key = 'sms_code_' + attrs.get('mobile')
        sms_code_redis = redis_cli.get(key)
        sms_code_request = attrs.get('sms_code')
        if not sms_code_redis:
            raise serializers.ValidationError('验证码已过期!')
        # 强制删除短信验证码
        redis_cli.delete('sms_code')
        if sms_code_redis.decode() != sms_code_request:
            raise serializers.ValidationError('验证码输入错误!')
        return attrs

    def create(self, validated_data):
        user = User()
        user.username = validated_data.get('username')
        user.mobile = validated_data.get('mobile')
        user.set_password(validated_data.get('password'))
        user.save()
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user


class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


# 设置用户邮箱
class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    # 重写update方法
    def update(self, instance, validated_data):
        email = validated_data['email']
        instance.email = validated_data['email']
        instance.save()
        # 生成激活链接
        verify_url = instance.generate_verify_email_url()
        # 发送邮箱激活链接
        send_email_verify.delay(email, verify_url)
        return instance


class UserAddressSerializer(serializers.ModelSerializer):
    # 关系属性默认输出主键,需重新定义省市区
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    # 默认属性重新定义才可使用
    province_id = serializers.IntegerField(label="省ID", required=True)
    city_id = serializers.IntegerField(label="市ID", required=True)
    district_id = serializers.IntegerField(label="区ID", required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_delete', 'create_time', 'update_time')

    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        # 用户是当前登录的用户 REST framework会向对象的context属性补充三个数据：
        # request、format、view，这三个数据对象可以在定义序列化器时使用。
        validated_data['user'] = self.context['request'].user
        # 调用
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = ('title',)


class AddUserBrowsingHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label="商品SKU编号", min_value=1)

    # 验证sku_id的有效性
    def validate_sku_id(self, value):
        try:
            SKU.objects.get(id=value)
        except:
            raise serializers.ValidationError('商品不存在')
        return value

    # 将用户浏览记录存入redis
    def create(self, validated_data):
        redis_cli = get_redis_connection('history')
        user_id = self.context.get('request').user.id
        sku_id = validated_data['sku_id']
        key = 'history_%d' % user_id
        redis_pl = redis_cli.pipeline()
        redis_pl.lrem(key, 0, sku_id)
        redis_pl.lpush(key, sku_id)
        redis_pl.ltrim(key, 0, USER_BROWSING_HISTORY_COUNTS_LIMIT - 1)
        redis_pl.execute()
        return validated_data
